﻿using System.Globalization;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;

namespace Mailer
{
	public static class HtmlExtentions
	{/*
		public static string Translate(this HtmlHelper htmlHelper, string tag)
		{
			htmlHelper.ViewContext.HttpContext.GetLocalResourceObject()

			var tagsplit = tag.Split('/');

			return htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(tagsplit[0], tagsplit[1], CultureInfo.CurrentUICulture).ToString();

			// return htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(htmlHelper.ViewContext.Controller.GetType().Name, tag);
			// return "TRANSLATED[" + htmlHelper.ViewContext.Controller.GetType().Name + "/" + tag + "]";
		}
		*/
		public static string Resource(this HtmlHelper htmlhelper, string expression, params object[] args)
		{
			string virtualPath = GetVirtualPath(htmlhelper);
			return GetResourceString(htmlhelper.ViewContext.HttpContext, expression, virtualPath, args);
		}

		public static string Resource(this Controller controller, string expression, params object[] args)
		{
			return GetResourceString(controller.HttpContext, expression, "~/", args);
		}

		private static string GetResourceString(HttpContextBase httpContext, string expression, string virtualPath, object[] args)
		{
			var context = new ExpressionBuilderContext(virtualPath);
			var builder = new ResourceExpressionBuilder();
			var fields = (ResourceExpressionFields)builder.ParseExpression(expression, typeof(string), context);

			if (!string.IsNullOrEmpty(fields.ClassKey))
				return string.Format((string)httpContext.GetGlobalResourceObject(fields.ClassKey, fields.ResourceKey, CultureInfo.CurrentUICulture), args);

			return string.Format((string)httpContext.GetLocalResourceObject(virtualPath, fields.ResourceKey, CultureInfo.CurrentUICulture), args);
		}

		private static string GetVirtualPath(HtmlHelper htmlhelper)
		{
			var view = htmlhelper.ViewContext.View as WebFormView;
			if (view != null)
				return view.ViewPath;

			return null;
		}
	}
}